package com.cai.xiaobai.config.jwt;


import com.cai.xiaobai.utils.RedisTool;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

import static com.cai.xiaobai.utils.TokenUtil.getOpenIdToken;


@Component
public class TokenHandler implements HandlerInterceptor {
    @Resource
    RedisTool redisTool;
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        try {
            String token = request.getHeader("token");
            if (Objects.isNull(token)) {
                return false;
            }
            String openId = getOpenIdToken(token);
            if (Objects.isNull(openId)) {
                return false;
            }
            Object cacheObject = redisTool.getCacheObject(openId);
            return !Objects.isNull(cacheObject);
        } catch (Exception e) {
            return false;
        }
    }
}
